import Vue from 'vue';
import wx from 'weixin-js-sdk';
import store from '@/store/';
import { USERINFO } from '@/store/mutation-types';
import { GetQuery } from './common';
import { jssdk } from './serve';

const wxAppid = process.env.VUE_APP_APPID;
const fromurl = window.location.href.split('#')[0];
const scopeType = 'snsapi_userinfo'; // 授权形式： 弹窗-snsapi_userinfo 静默-snsapi_base

export function getCode(BackUrl = '') {
  let backurl = BackUrl;
  // 设置 backurl, 微信会跳回指定地址，若不设置，默认到首页
  if (BackUrl) backurl = `#${backurl}`;
  return new Promise((resolve, reject) => {
    const code = GetQuery('code');
    if (!code && !Vue.ls.get(USERINFO) && process.env.NODE_ENV !== 'development') {
      const url = `//open.weixin.qq.com/connect/oauth2/authorize?appid=${wxAppid}&redirect_uri=${encodeURIComponent(fromurl + backurl)}&response_type=code&scope=${scopeType}&state=STATE#wechat_redirect`;
      window.location.replace(url);
    } else {
      store.dispatch('UserInfo', code).then((res) => {
        resolve(res);
      }).catch((err) => {
        reject(err);
      });
    }
  });
}

export function wxShare(shareData) {
  wx.ready(() => {
    const d = {
      title: '默认分享标题',
      desc: '默认分享内容',
      link: fromurl, // 默认分享地址
      imgUrl: 'https://static1.nbpitech.com/checkin/static/Image/logo.png' // 默认分享图标
    };

    const shares = {
      ...Object.assign(d, shareData),
      success() {
      }
    };
    wx.onMenuShareAppMessage(shares);
    wx.onMenuShareTimeline(shares);
  });
}

export function getJSSDK(shareData) {
  return new Promise((resolve) => {
    jssdk({ url: fromurl }).then((res) => {
      const r = res.data;
      wx.config({
        debug: false,
        appId: r.appId,
        timestamp: r.timestamp,
        nonceStr: r.nonceStr,
        signature: r.signature,
        jsApiList: [
          'checkJsApi',
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'onMenuShareQQ',
          'onMenuShareWeibo',
          'hideMenuItems',
          'showMenuItems',
          'hideAllNonBaseMenuItem',
          'showAllNonBaseMenuItem',
          'translateVoice',
          'startRecord',
          'stopRecord',
          'onRecordEnd',
          'playVoice',
          'pauseVoice',
          'stopVoice',
          'uploadVoice',
          'downloadVoice',
          'chooseImage',
          'previewImage',
          'uploadImage',
          'downloadImage',
          'getNetworkType',
          'openLocation',
          'getLocation',
          'hideOptionMenu',
          'showOptionMenu',
          'closeWindow',
          'scanQRCode',
          'chooseWXPay',
          'openProductSpecificView',
          'addCard',
          'chooseCard',
          'openCard'
        ]
      });
      wxShare(shareData);
      resolve();
    });
  });
}
